<?php

namespace Rblog\Module\Admin\Controller;

class Artwrite extends Index {
    private $_model;
    private $_sortData;
    
    public function __construct() {
        $this->_working = 'artwrite';
        parent::__construct();
        $this->_model = \Rexzy::model( 'Arts' );
        $this->_sortData = \Rexzy::model( 'Artsort' );
    }
    
    /**
     * 显示撰写文章的编辑器
     */
    public function show() {
        $this->view->assign('artsort', $this->_sortData);
        $this->view->display();
    }
    
    /**
     * 发布新文章
     */
    public function issue() {
        $post = $this->request->AllInput( 'p' );
        
        if ( $post['arttitle'] == '' ) {
            echo json_encode( array( 'issueResult' => false, 'error' => '请输入文章标题' ) );
            return false;
        } else if ( $post['art'] == '' ) {
            echo json_encode( array( 'issueResult' => false, 'error' => '请输入文章内容' ) );
            return false;
        } else if ( $post['sortval'] == '' ) {
            echo json_encode( array( 'issueResult' => false, 'error' => '请选择文章分类' ) );
            return false;
        } else if ( $post['date'] == '' ) {
            echo json_encode( array( 'issueResult' => false, 'error' => '请输入发布日期' ) );
            return false;
        } else if ( $post['outline'] == '' ) {
            echo json_encode( array( 'issueResult' => false, 'error' => '请输入文章概要' ) );
            return false;
        }
        
        
        if ( $this->_model->existTitle( $post['arttitle'] ) > 0 ) {
            echo json_encode( array( 'issueResult' => false, 'error' => '文章标题已存在，请重新输入') );
            return false;
        }
        
        $artMesg = array(
            'content' => $post['art'],
            'title' => $post['arttitle'],
            'sort' => $post['sortval'],
            'date' => strtotime( $post['date'] ),
            'author' => $this->_screenName,
            'outline' => $post['outline']
        );
        $result = $this->_model->addArt( $artMesg );
        
        if ( $result == true ) {
            echo json_encode( array( 'issueResult' => true ) );
        } else {
            echo json_encode( array( 'issueResult' => false, 'error' => '数据读写异常，请稍后再试' ) );
        }
    }
    
    /**
     * 编辑文章
     */
    public function edit() {
        if ( $this->request->isPost() != true ) {
            $artid = $this->request->input( 'artid', 'g' );
            $artMesg = $this->_model->getMesg( $artid );
            $artMesg['date'] = date( 'Y-m-d', $artMesg['date'] );

            $this->view->assign( array( 
                'artMesg' => $artMesg,
                'artsort' => $this->_sortData,
                'handleUrl' => \Rexzy::url( 'admin/artedit' ),
                'work' => 'artlist',
                'artlistUrl' => \Rexzy::url( 'admin/artlist' )
                ) );
            $this->view->display();
            
        } else {
            $post = $this->request->AllInput( 'p' );
            
            if ( $post['arttitle'] == '' ) {
                echo json_encode( array( 'issueResult' => false, 'error' => '请输入文章标题' ) );
                return false;
            } else if ( $post['art'] == '' ) {
                echo json_encode( array( 'issueResult' => false, 'error' => '请输入文章内容' ) );
                return false;
            } else if ( $post['sortval'] == '' ) {
                echo json_encode( array( 'issueResult' => false, 'error' => '请选择文章分类' ) );
                return false;
            } else if ( $post['date'] == '' ) {
                echo json_encode( array( 'issueResult' => false, 'error' => '请输入发布日期' ) );
                return false;
            } else if ( $post['outline'] == '' ) {
                echo json_encode( array( 'issueResult' => false, 'error' => '请输入文章概要' ) );
                return false;
            }

            $artMesg = array(
                'content' => $post['art'],
                'title' => $post['arttitle'],
                'sort' => $post['sortval'],
                'date' => strtotime( $post['date'] ),
                'artid' => $post['artid'],
                'outline' => $post['outline']
            );
            $result = $this->_model->edit( $artMesg );
            if( $result > 0 ) {
                echo json_encode( array( 'issueResult' => true ) );
            } else if ($result == 0 ){
                echo json_encode( array( 'issueResult' => false, 'error' => '没有要更新的内容，请确认！' ) );
            }
        }
    }
    
    /**
     * 处理上传文件
     */
    public function uploadfile() {
//        $ext_arr = array( 'gif', 'jpg', 'jpeg', 'png', 'bmp' );
//        
//        if ( empty( $_FILES ) === false ) {
//            $file_name = $_FILES['imgFile']['name'];
//            $tmp_name = $_FILES['imgFile']['tmp_name'];
//            
//            $save_dir = APP_PATH . '/statics/uploadfile/';
//            if ( ! file_exists( $save_dir ) ){
//                mkdir( $save_dir );
//            }
//            move_uploaded_file($tmp_name, $save_dir.$file_name );
//            $file_url = \Rexzy::getConfig( 'url') . '/statics/uploadfile/' . $file_name;
//            
//            echo json_encode(array('error' => 0, 'url' => $file_url) );
//            exit;
//        }
        
        $php_path = APP_PATH . '/';
        $php_url = \Rexzy::getConfig( 'url');

        //文件保存目录路径
        $save_path = $php_path . '/statics/uploadfile/';
        //文件保存目录URL
        $save_url = $php_url . '/statics/uploadfile/';
        //定义允许上传的文件扩展名
        $ext_arr = array(
            'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
            'flash' => array('swf', 'flv'),
            'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
            'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
        );
        //最大文件大小
        $max_size = 1000000;

        $save_path = realpath($save_path) . '/';

        //PHP上传失败
        if (!empty($_FILES['imgFile']['error'])) {
            switch($_FILES['imgFile']['error']){
                case '1':
                    $error = '超过php.ini允许的大小。';
                    break;
                case '2':
                    $error = '超过表单允许的大小。';
                    break;
                case '3':
                    $error = '图片只有部分被上传。';
                    break;
                case '4':
                    $error = '请选择图片。';
                    break;
                case '6':
                    $error = '找不到临时目录。';
                    break;
                case '7':
                    $error = '写文件到硬盘出错。';
                    break;
                case '8':
                    $error = 'File upload stopped by extension。';
                    break;
                case '999':
                default:
                    $error = '未知错误。';
            }
            $this->alert($error);
        }

        //有上传文件时
        if (empty($_FILES) === false) {
            //原文件名
            $file_name = $_FILES['imgFile']['name'];
            //服务器上临时文件名
            $tmp_name = $_FILES['imgFile']['tmp_name'];
            //文件大小
            $file_size = $_FILES['imgFile']['size'];
            //检查文件名
            if (!$file_name) {
                $this->alert("请选择文件。");
            }
            //检查目录
            if (@is_dir($save_path) === false) {
                $this->alert("上传目录不存在。");
            }
            //检查目录写权限
            if (@is_writable($save_path) === false) {
                $this->alert("上传目录没有写权限。");
            }
            //检查是否已上传
            if (@is_uploaded_file($tmp_name) === false) {
                $this->alert("上传失败。");
            }
            //检查文件大小
            if ($file_size > $max_size) {
                $this->alert("上传文件大小超过限制。");
            }
            //检查目录名
            $dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);
            if (empty($ext_arr[$dir_name])) {
                $this->alert("目录名不正确。");
            }
            //获得文件扩展名
            $temp_arr = explode(".", $file_name);
            $file_ext = array_pop($temp_arr);
            $file_ext = trim($file_ext);
            $file_ext = strtolower($file_ext);
            //检查扩展名
            if (in_array($file_ext, $ext_arr[$dir_name]) === false) {
                $this->alert("上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。");
            }
            //创建文件夹
            if ($dir_name !== '') {
                $save_path .= $dir_name . "/";
                $save_url .= $dir_name . "/";
                if (!file_exists($save_path)) {
                    mkdir($save_path);
                }
            }
            $ymd = date("Ymd");
            $save_path .= $ymd . "/";
            $save_url .= $ymd . "/";
            if (!file_exists($save_path)) {
                mkdir($save_path);
            }
            //新文件名
            $new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
            //移动文件
            $file_path = $save_path . $new_file_name;
            if (move_uploaded_file($tmp_name, $file_path) === false) {
                $this->alert("上传文件失败。");
            }
            @chmod($file_path, 0644);
            $file_url = $save_url . $new_file_name;

            echo json_encode(array('error' => 0, 'url' => $file_url));
            exit;
        }
    }
    
    /**
     * 文件上传异常处理
     */
    public function alert( $msg ) {
        echo json_encode(array('error' => 1, 'message' => $msg));
        exit;
    }
}
